﻿using Coomtools.weightclasses;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CYLScheck.UIcomm
{


    public partial class TranfEweightFrm : UIForm
    {
        const string SaveEweightsFilePath = "EweightsSaved.dat";
        private BindingList<Uipluitem> uiplulist;
        int AllPluCount=0;
        List<EweightModel> EweightList = new List<EweightModel>();
    
        public TranfEweightFrm(BindingList<Uipluitem> Inplulist)
        {
            InitializeComponent();
            uiplulist = Inplulist;


        }
        Dictionary<string, string> D_Getweights = new Dictionary<string, string>();
        /// <summary>
        /// 获得支持称电子称协议
        /// </summary>
        /// <param name="d_Getweights"></param>
        /// <returns></returns>
        Dictionary<string, string> GetAssemblyweightclasses(Dictionary<string, string> d_Getweights)
        {
            Assembly Getweightsasm;

            try
            {        ///反射 dll程序集
                Getweightsasm = Assembly.LoadFrom("Coomtools.dll");
                //反射  改程序集中对应的  电子称信息汇聚类
                Type WeightType = Getweightsasm.GetType("Coomtools.weightclasses.Myweightclasses");
                // 反射  实例化该  电子信息汇聚类
                object MyWeights = Activator.CreateInstance(WeightType);
                // 对 字典类型的   获得到的电子称集合赋值
                d_Getweights.Clear();
                return d_Getweights = (Dictionary<string, string>)WeightType.GetField("Allweights").GetValue(MyWeights);


            }
            catch (Exception)
            {
               
                MessageBox.Show("获得支持的电子称协议失败！");
                return null;
                //throw;
            }

        }
        /// <summary>
        /// 添加行实现1
        /// </summary>
        void AddMyRow1()
        {
            //先添加一行
            uiDataGridView1.AddRow();
            int lastrow;
            lastrow = uiDataGridView1.Rows.Count - 1;
            uiDataGridView1.Rows[lastrow].Cells["IsSelected"].Value = true;
            uiDataGridView1.Rows[lastrow].Cells["IsTranfHotKey"].Value = false;
            uiDataGridView1.Rows[lastrow].Cells["Eweightmodel"].Value = "通用";
            List<string> ls = new List<string>();
            ls.Add("请选择");
            DataGridViewComboBoxCell dcell = (DataGridViewComboBoxCell)uiDataGridView1.Rows[lastrow].Cells["weightAgreement"];

            foreach (var item in D_Getweights.Keys)
            {
                ls.Add(item.ToString());
            }

            foreach (var item in ls)
            {
                dcell.Items.Add(item);
            }
            dcell.Value = ls[0];
            //初始化可删除测试方便用
            uiDataGridView1.Rows[lastrow].Cells["EweightIP"].Value = "192.168.0.87";
            uiDataGridView1.Rows[lastrow].Cells["Eweightport"].Value = "3001";


        }
        #region 另一种添加行的方式有bug 暂时不用需要时解决
///// <summary>
        ///// 另一种添加行的方式有bug 暂时不用需要时解决
        ///// </summary>
        //void AddMyRow2()
        //{
        //    int lastrow;
        //    lastrow = uiDataGridView1.Rows.Count ;
        //    DataTable dt = new DataTable();
        //    dt.Columns.Add(new DataColumn("key"));
        //    dt.Columns.Add(new DataColumn("value"));
        //    DataRow drow2 = dt.NewRow();
        //    drow2["key"] = "请选择";
        //    drow2["value"] = "";
        //    dt.Rows.Add(drow2);


        //    foreach (var item in D_Getweights)
        //    {  DataRow drow = dt.NewRow();
        //        drow["key"] = item.Key;
        //        drow["value"] = item.Value;
        //        dt.Rows.Add(drow);

        //    }

        //    DataGridViewComboBoxColumn dgcombobox = (DataGridViewComboBoxColumn)uiDataGridView1.Columns["weightAgreement"];
        //    dgcombobox.DataSource = dt;
        //    dgcombobox.DataPropertyName = "key";
        //    dgcombobox.DisplayMember = "key";
        //    dgcombobox.ValueMember = "key";
        //    DataGridViewComboBoxCell dcell = (DataGridViewComboBoxCell)uiDataGridView1.Rows[lastrow].Cells["weightAgreement"];
        //    dcell.Value = dt.Rows[1][0];

        //}
        #endregion
        

        void SetUITranfInfoClear(UIDataGridView dgv, int row)
        {

            dgv.Rows[row].Cells["TranfProgress"].Value = "";
            dgv.Rows[row].Cells["TranfResult"].Value = "";
        }

       void SetUITranWaiting(UIDataGridView dgv, int row, int index, int total)
        {
            dgv.Rows[row].Cells["TranfProgress"].Value = "等待开始..." ;
            dgv.Rows[row].Cells["TranfResult"].Value = "已选择 ";
        }


        void SetUITranfError(UIDataGridView dgv, int row, int index, int total)
        {


            dgv.Rows[row].Cells["TranfProgress"].Value = "传输: " + index.ToString() + " / " + "总数:" + total.ToString();
            dgv.Rows[row].Cells["TranfResult"].Value = "传输失败! ";
        }
        public void SetUITranfInfo(UIDataGridView dgv, int row,int index,int total,string Tranfhotkeymessage)
            
        {
            //TranfProgress
            //TranfResult
            dgv.Rows[row].Cells["TranfProgress"].Value = "PLU传输: " + index.ToString() + "/" + "总数:" + total.ToString();
            dgv.Rows[row].Cells["TranfResult"].Value = "PLU传输成功! "+Tranfhotkeymessage; 

        }
        private void TranfEweightFrm_Load(object sender, EventArgs e)
        {
            AllPluCount = uiplulist.Count;
            this.Style = Gobleset.Gobel_userstyle;
            D_Getweights = GetAssemblyweightclasses(D_Getweights);

            //不绑定不需要的列
            uiDataGridView1.AutoGenerateColumns = false;
          //不能自动增加行
            uiDataGridView1.AllowUserToAddRows = false;
           
            //不能多选
            uiDataGridView1.MultiSelect = false;
          //选择整行
            uiDataGridView1.SelectionMode=DataGridViewSelectionMode.FullRowSelect;   
          // 行前不显示三角
            uiDataGridView1.RowHeadersVisible=false;

            //**********************启动读取保存的电子秤列表反序列化出list************************
            FileToObject();
            if (EweightList.Count>0)
            {  
                int newrow=0;
                foreach (var item in EweightList)
                {
                  
                    uiDataGridView1.AddRow();
                 
                    uiDataGridView1.Rows[newrow].Cells["IsSelected"].Value = item.Isuse;
                    uiDataGridView1.Rows[newrow].Cells["IsTranfHotKey"].Value = item.Isuse;
                    
                    //uiDataGridView1.Rows[0].Cells["weightAgreement"];

                    uiDataGridView1.Rows[newrow].Cells[2].Value = item.TheWeightModel;
             
                    uiDataGridView1.Rows[newrow].Cells["EweightIP"].Value = item.IPAdress;
                    uiDataGridView1.Rows[newrow].Cells["Eweightport"].Value = item.Port;

                    DataGridViewComboBoxCell dcell = (DataGridViewComboBoxCell)uiDataGridView1.Rows[newrow].Cells["weightAgreement"];
                    List<string> ls = new List<string>();
                    foreach (var key in D_Getweights.Keys)
                    {
                        ls.Add(key.ToString());
                    }
                    foreach (var ite in ls)
                    {
                        dcell.Items.Add(ite);
                    }
                    dcell.Value = item.Useagreement;
                    newrow++;


                }



            }
            SetUIcellInfo(uiDataGridView1);
            uiLable_message.Text = uiLable_message.Text +  AllPluCount.ToString() + " 个";

        }

        private void bt_AddEweight_Click(object sender, EventArgs e)
        {


            AddMyRow1();

        }

        private void bt_DelEweight_Click(object sender, EventArgs e)
        {
           //防止空删除 或没有选择就删除行 而报错
            if (uiDataGridView1.RowCount>0 || uiDataGridView1.CurrentCell !=null)
            {
               int selectrow;
               selectrow = uiDataGridView1.SelectedRows[0].Index;
               uiDataGridView1.Rows.RemoveAt(selectrow);
            }
        
        }
      //string  GetAssemblyweightclassesNameValue(string Eweigtagement)
      //  {
      //      Assembly Getweightsasm;
      //      Dictionary<string, string> Getweights = new Dictionary<string, string>();
      //      try
      //      {        ///反射 dll程序集
      //          Getweightsasm = Assembly.LoadFrom("Coomtools.dll");
      //          //反射  改程序集中对应的  电子称信息汇聚类
      //          Type WeightType = Getweightsasm.GetType("Coomtools.weightclasses.Myweightclasses");
      //          // 反射  实例化该  电子信息汇聚类
      //          object MyWeights = Activator.CreateInstance(WeightType);
      //          // 对 字典类型的   获得到的电子称集合赋值
      //          Getweights = (Dictionary<string, string>)WeightType.GetField("Allweights").GetValue(MyWeights);

      //          foreach (var key in Getweights.Keys)
      //          {
      //              if (key==Eweigtagement)
      //              {
      //                  return Getweights[key];
      //              }
      //          }

      //          return "NOclasses";

      //      }
      //      catch (Exception)
      //      {

      //          throw;
      //      }

      //  }
   /// <summary>
   /// 开始传输电子称
   /// </summary>
        public void StartTranfEWeights()
        {
              if (uiDataGridView1.Rows.Count > 0)
               {
                //循环可用电子秤列表
                for (int i = 0; i < uiDataGridView1.Rows.Count; i++)
                {
                    SetUITranfInfoClear(uiDataGridView1, i);
                    bool Isuse =false;
                    bool IsTranfhotkey = false;
                    string TheWeightModel = "";
                    string IPAdress = "";
                    string Port = "";
                    Isuse = (bool)uiDataGridView1.Rows[i].Cells["IsSelected"].Value;
                    IsTranfhotkey= (bool)uiDataGridView1.Rows[i].Cells["IsTranfHotKey"].Value;
                    TheWeightModel = uiDataGridView1.Rows[i].Cells["Eweightmodel"].Value.ToString().Trim();
                    IPAdress = uiDataGridView1.Rows[i].Cells["EweightIP"].Value.ToString().Trim();
                     Port = uiDataGridView1.Rows[i].Cells["Eweightport"].Value.ToString().Trim();
                    //需要根据具体协议名称生成 该协议对象用于传送
                    string Useagreement = uiDataGridView1.Rows[i].Cells["weightAgreement"].Value.ToString();

                    if (Isuse && Useagreement!="请选择"&& IPAdress!="")
                    {
                       
                        //***********生成具体协议对象
                        ///反射 dll程序集
                        #region *************传电子秤核心过程******************
                        try
                    {
                        Assembly Getweightsasm;

                        Getweightsasm = Assembly.LoadFrom("Coomtools.dll");
                        //反射  改程序集中对应的  所需要的电子称类
                        string UseClassName = D_Getweights.GetValue(Useagreement);
                        Type WeightType = Getweightsasm.GetType("Coomtools.weightclasses." + UseClassName);

                        // 反射  实例化该  电子称类，必须为 参数 的构造方法
                        object UseWeight = Activator.CreateInstance(WeightType, (new object[] { uiplulist }));
                        //***************具体操作类方法获取********

                            MethodInfo minfolink = WeightType.GetMethod("Link_EWeightOK");
                            MethodInfo minfoTranfPLU = WeightType.GetMethod("StartTranfPLU");
                            MethodInfo minfoTranfHotKey = WeightType.GetMethod("StartTranHotKey");
                            MethodInfo mifoCloseConnect = WeightType.GetMethod("Close_EWeightConnect");

                            bool IsLinkOK = (bool)minfolink.Invoke(UseWeight, new object[] { IPAdress, Port });
                        
                            if (IsLinkOK)
                        {
                                //******开始界面传送时候的动画效果  ********

                                if (this.IsHandleCreated)
                                {
                               this.Invoke( new MethodInvoker(() =>
                                {
                                    stick = "";
                                    tick = 0;
                                  
                                    uiLabel_proess.Text = "正在下传电子秤地址：" + IPAdress;
                                    tranfprogessui = uiLabel_proess.Text;
                                    timer1.Start();
                                }));
                                }
                                

                            int succ = (int)minfoTranfPLU.Invoke(UseWeight, new object[] { IPAdress, Port });
                            if (succ > 0)
                            {
                                //MessageBox.Show("PLU传输成功");
                                SetUITranfInfo(uiDataGridView1, i, succ, AllPluCount,"");
                                    //******开始界面传送时候的动画效果关闭  ********
                                    StopUiTranfAnimation(IPAdress,"下传成功完毕！");

                                }

             
                                else
                                {
                                 SetUITranfError(uiDataGridView1, i, succ, AllPluCount);
                                    //******界面传送时候的动画效果关闭  ********
                                    StopUiTranfAnimation(IPAdress,"下传错误！");
                                }
                                
                        }
                        else
                        {
                            SetUITranfError(uiDataGridView1, i, 0, AllPluCount);
                                //******错误时 界面传送时候的动画效果关闭  ********
                                ErrorStopAnimation(IPAdress);
                            }
                        //*******当传送PLU没有异常成功后再传热键*******   
                        //*******   开始传输热键*******   
                        if (IsTranfhotkey)
                        {
                                IsLinkOK = (bool)minfolink.Invoke(UseWeight, new object[] { IPAdress, Port });
                            if (IsLinkOK)
                            {
                                int SendHotKeyNum = (int)minfoTranfHotKey.Invoke(UseWeight, new object[] { IPAdress, Port });
                                //返回值大于等于0表示成功
                                if (SendHotKeyNum > 0)

                                {
                                        //SetUITranfInfo(uiDataGridView1, i, succ, AllPluCount, "热键已下传！");
                                      uiDataGridView1.Rows[i].Cells["TranfResult"].Value = uiDataGridView1.Rows[i].Cells["TranfResult"].Value.ToString() + SendHotKeyNum.ToString() + "个热键已下传！";
                                    
                                    
                                    }
                                else
                                        uiDataGridView1.Rows[i].Cells["TranfResult"].Value = uiDataGridView1.Rows[i].Cells["TranfResult"].Value.ToString() + "热键下传异常！" + SendHotKeyNum.ToString();
                                }

                            else
                          
                                uiDataGridView1.Rows[i].Cells["TranfResult"].Value = uiDataGridView1.Rows[i].Cells["TranfResult"].Value.ToString() + "电子秤连接失败无法下载热键！";
                   
                            }
                            //*******结束传输热键*******   
                          bool ClosedOK=  (bool)mifoCloseConnect.Invoke(UseWeight, new object[] { IPAdress, Port });

                        }
                    catch (Exception )
                    {

                            //******错误时 界面传送时候的动画效果关闭  ********
                            ErrorStopAnimation(IPAdress);
                            //bool ClosedOK = (bool)mifoCloseConnect.Invoke(UseWeight, new object[] { IPAdress, Port });
                            UIMessageDialog.ShowErrorDialog(this,"称地址:"+IPAdress+" 发生传输错误！",UIStyle.Red);
                    }
                    
                   
                  
                    #endregion
                
                    }
                   }


                //******界面传送时候的动画效果关闭  ********
                StopUiTranfAnimation("全部需下传电子称，", "下载过程结束！");
            }
           //可用电子秤列表里没有选项
            else
                UIMessageBox.Show("没有要传的电子称！");
        }


        /// <summary>
        /// 界面传送时候的动画效果关闭 
        /// </summary>
        void StopUiTranfAnimation(string IPAdress,string message)
        {
            //******界面传送时候的动画效果关闭  ********

            if (this.IsHandleCreated)
            {
                 this.Invoke(new MethodInvoker(() =>
            {
                
                stick = "";
                tick = 0;

                uiLabel_proess.Text = "电子秤:" + IPAdress + message;
                tranfprogessui = "";
                timer1.Stop();
            }));
            }
           
        }
        void ErrorStopAnimation(string IPAdress)
        {
            //******界面传送时候的动画效果关闭  ********

            if (this.IsHandleCreated)
            {
                this.Invoke(new MethodInvoker(() =>
                {

                    stick = "";
                    tick = 0;

                    uiLabel_proess.Text = "电子秤:"+IPAdress+" 连接失败!";
                    tranfprogessui = "";
                    timer1.Stop();
                }));
            }

        }
        private void uiButton2_Click(object sender, EventArgs e)
        {
            uiLabel_proess.Text = "开始下传电子秤";
            Thread Tstart = new Thread(new ThreadStart(StartTranfEWeights));
            Tstart.Start();
         

              
            }
        /// <summary>
        /// 将文件"EweightsSaved.dat"反序列化为类
        /// </summary>
        void FileToObject()
        {
            if (File.Exists(SaveEweightsFilePath))
            {
                   using (FileStream stream = new FileStream(SaveEweightsFilePath, FileMode.Open))
                              {
                                BinaryFormatter formatter = new BinaryFormatter();
                                EweightList = formatter.Deserialize(stream) as List<EweightModel>;
                           
                           }
            }

    

        }

        private void Btton_Save_Click(object sender, EventArgs e)
        {
            //将界面的可用电子秤信息转换为EweightModel类的List用于序列化
            try
            {
                     EweightList.Clear();
                     for (int i = 0; i < uiDataGridView1.Rows.Count; i++)
            {
                
                EweightModel ew = new EweightModel();
                ew.Isuse = (bool)uiDataGridView1.Rows[i].Cells["IsSelected"].Value;
                ew.TheWeightModel = uiDataGridView1.Rows[i].Cells["Eweightmodel"].Value.ToString().Trim();
                ew.IPAdress = uiDataGridView1.Rows[i].Cells["EweightIP"].Value.ToString().Trim();
                ew.Port = uiDataGridView1.Rows[i].Cells["Eweightport"].Value.ToString().Trim();
                ew.IsTranfHotKey = (bool)uiDataGridView1.Rows[i].Cells["IsTranfHotKey"].Value;
                //需要根据具体协议名称生成 该协议对象用于传送
                ew.Useagreement = uiDataGridView1.Rows[i].Cells["weightAgreement"].Value.ToString();
                if (ew.Useagreement!="请选择")
                {
                 EweightList.Add(ew);
                }
               

            }

                     if (EweightList.Count>0)
            {
                //********************************序列化文件**************************************
                             BinaryFormatter formatter = new BinaryFormatter();
                              using (FileStream stream = new FileStream(SaveEweightsFilePath, FileMode.OpenOrCreate))
                                {
                                    formatter.Serialize(stream, EweightList);
                                  }
                        UIMessageBox.Show("可用电子秤列表保存成功！");
         
              
                }

            }
            catch (Exception)
            {
            UIMessageDialog.ShowErrorDialog(new Form(),"保存失败！",UIStyle.Red);
            }
   


    }
        void SetUIcellInfo(UIDataGridView dgv)
        {
            if (dgv.Rows.Count>0)
            {
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    if ((bool)dgv.Rows[i].Cells["IsSelected"].Value)
                    {
                        dgv.Rows[i].Cells["TranfResult"].Value = "已选择";
                        dgv.Rows[i].Cells["TranfProgress"].Value = "等待开始...";
                    }
                    else
                    {
                        dgv.Rows[i].Cells["TranfResult"].Value = "未选择"; 
                        dgv.Rows[i].Cells["TranfProgress"].Value = "已取消操作...";
                    }
                }

            }
        }
        private void uiDataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
                  if (uiDataGridView1.IsCurrentCellDirty)
            {
                uiDataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
       
        
        }

        private void uiDataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.RowIndex != -1 && !uiDataGridView1.Rows[e.RowIndex].IsNewRow)
            {
                if (e.ColumnIndex == 0)
                {
              if ((bool)uiDataGridView1.Rows[e.RowIndex].Cells["IsSelected"].Value)
                    {
                        uiDataGridView1.Rows[e.RowIndex].Cells["TranfResult"].Value = "已选择";
                        uiDataGridView1.Rows[e.RowIndex].Cells["TranfProgress"].Value = "等待开始...";

                    }

                    else
                    {

                        uiDataGridView1.Rows[e.RowIndex].Cells["TranfResult"].Value = "未选择";
                        uiDataGridView1.Rows[e.RowIndex].Cells["TranfProgress"].Value = "已取消操作...";
                    }

                }


            }

    

        }
        int tick;
        string stick="";
        string tranfprogessui;
        /// <summary>
        /// 实现界面动画效果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
       
                if (tick<3)
                {
                stick = stick + ">";
                uiLabel_proess.Text = uiLabel_proess.Text + stick;
                tick++;
                }
                else
            {
                tick = 0;
                stick = "";
                uiLabel_proess.Text = tranfprogessui;
            }



          
        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
